<template>
  <div>
    <keyBoard :list="list" :keyCode="keyCode" @choseKeyCode="choseKeyCode"></keyBoard>
    <controllBox :power.sync="power" :bank.sync="bank" ref="controllBox" :name="name"></controllBox>
    <audio src="" ref="audio" @canplay="$event.target.play()"></audio>
  </div>
</template>

<script>
import keyBoard from './keyBoard'
import controllBox from './controllBox'
import axios from 'axios'

export default {
  components: {
    keyBoard,
    controllBox
  },
  data () {
    return {
      list: [],
      musicType: 0,
      power: true, // 使能按键
      bank: true, // 音色按键
      keyCode: 0, // 声音按键
      name: ''
    }
  },
  created () {
    this.getData()
  },
  mounted () {
    console.log(this.$refs.controllBox)
  },
  methods: {
    // 获取数据
    async getData () {
      try {
        const res = await axios('http://121.89.213.194:3001/api/music')
        this.list = res.data.data
        console.log(this.list)
      } catch (error) {
        console.log(error)
      }
    },
    // 处理键盘传回的键值
    choseKeyCode (keyCode) {
      if (!this.power) return
      this.keyCode = keyCode
      const obj = (this.list.find(item => item.keyCode === this.keyCode))
      this.name = obj ? obj.id : ''
      this.$refs.audio.volume = this.$refs.controllBox.volume
      if (obj) {
        if (this.bank) {
          this.$refs.audio.src = obj.url
        } else {
          this.$refs.audio.src = obj.bankUrl
        }
      } else {
        return
      }
      const timer = setTimeout(() => {
        this.keyCode = 0
        clearTimeout(timer)
      }, 200)
    }
  }
}
</script>

<style scoped>
  div {
    width: 1200px;
    height: 700px;
    display: flex;
    padding: 60px;
    border-radius: 50px;
    margin: -400px auto;
    justify-content: space-between;
    background-color: #eaecf9;
    box-shadow: 3px 3px 15px 5px black, 0 0 7px 7px rgba(0, 0, 0, 0.3) inset;
  }
</style>
